type ThrottledFunction<T extends (...args: any[]) => any> = (
  ...args: Parameters<T>
) => ReturnType<T> | void

export default {
  setLocal(name: string, data: any) {
    window.localStorage.setItem(name, data)
  },
  getLocal(name: string) {
    return window.localStorage.getItem(name)
  },
  deleteLocal(name: string) {
    window.localStorage.removeItem(name)
  },
  hasLocal(name: string) {
    const res = window.localStorage.keys().includes(name)
    return res
  },
  clearLocal() {
    window.localStorage.clear()
  },
  typeOf(obj: any): any {
    const toString: any = Object.prototype.toString
    const map: any = {
      '[object Boolean]': 'boolean',
      '[object Number]': 'number',
      '[object String]': 'string',
      '[object Function]': 'function',
      '[object Array]': 'array',
      '[object Date]': 'date',
      '[object RegExp]': 'regExp',
      '[object Undefined]': 'undefined',
      '[object Null]': 'null',
      '[object Object]': 'object'
    }
    return map[toString.call(obj)]
  },
  deepClone<T>(data: T): Promise<T> {
    return new Promise((resolve) => {
      const { port1, port2 } = new MessageChannel()
      port1.postMessage(data)
      port2.onmessage = (msg) => {
        resolve(msg.data)
      }
    })
  },
  calculateTotalPages(totalRecords: number, recordsPerPage: number) {
    return Math.ceil(totalRecords / recordsPerPage)
  },
  // 队列执行
  queueExecute(funcs: Array<() => void>, interval: number): void {
    if (!Array.isArray(funcs) || funcs.length === 0) {
      console.error('函数数组不能为空')
      return
    }
    if (typeof interval !== 'number' || interval <= 0) {
      console.error('时间间隔必须是正数')
      return
    }
    let index = 0
    function executeNext(): void {
      if (index < funcs.length) {
        try {
          funcs[index]() // 执行当前函数
        } catch (error) {
          console.error('函数执行出错:', error)
        }
        index++
        setTimeout(executeNext, interval) // 延迟执行下一个函数
      }
    }
    executeNext()
  },
  /**
   * 节流函数包装器
   * @param func 需要节流的原函数
   * @param wait 节流时间间隔（毫秒）
   * @param options 配置选项
   * @param options.leading 是否在节流开始时执行（默认 true）
   * @param options.trailing 是否在节流结束时执行（默认 true）
   */
  throttle<T extends (...args: any[]) => any>(
    func: T,
    wait: number,
    options?: { leading?: boolean; trailing?: boolean }
  ): ThrottledFunction<T> {
    let timeout: ReturnType<typeof setTimeout> | null = null
    let lastExecTime = 0
    let lastArgs: Parameters<T> | null = null
    let lastThis: any

    // 配置默认值
    const { leading = true, trailing = true } = options || {}

    const throttled = function (this: any, ...args: Parameters<T>) {
      const now = Date.now()

      // 处理 leading=false 的首次调用
      if (!lastExecTime && leading === false) {
        lastExecTime = now
      }

      const remaining = wait - (now - lastExecTime)

      // 立即执行条件
      if (remaining <= 0) {
        if (timeout) {
          clearTimeout(timeout)
          timeout = null
        }
        lastExecTime = now
        return func.apply(this, args)
      }

      // 设置延迟执行
      if (!timeout && trailing) {
        timeout = setTimeout(() => {
          lastExecTime = Date.now()
          timeout = null

          // 执行最后一次保存的上下文和参数
          if (lastArgs) {
            func.apply(lastThis, lastArgs)
            lastArgs = null
            lastThis = null
          }
        }, remaining)
      }

      // 保存最后一次调用的参数和上下文
      if (trailing) {
        lastArgs = args
        // 避免直接存储 this 引用
        lastThis = undefined
      }
    }

    return throttled
  }
}
